#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os, time
from datetime import datetime
import threading
from threading import Thread
import json
import csv

from flask import make_response, abort
from flask import request

from loguru import logger

sys.path.append(os.getcwd())
from utils import app_config
from utils import serialport_com
from utils import call_acq_control_driver
from utils import voltageSerialCommand

from webapi.matlab_engine import matlab_eng
import webapi.pai_global
from webapi.pai_acquisition_controll import AcquisitionControl

# 仅执行一次
webapi.pai_global._init()

## 获取所有的串口
def read_all_com_ports():
    logger.debug("start read_all_com_ports. ")
    acq_controll = webapi.pai_global.get_value("AcquisitionControl")
    portcom = acq_controll.getComPorts()

    com_ports = {"com_ports": [], "default_com_ports":{}}
    for key in portcom.keys():
        com_ports.get("com_ports").append(key)
    
    default_ports = acq_controll.getDefaultComPorts()
    default_com_ports = com_ports.get("default_com_ports")
    default_com_ports.update(default_ports)

    logger.debug("end read_all_com_ports.")
    return com_ports, 200

def set_voltage(positive_com_port, negative_com_port, voltage):
    logger.debug("query parameters: positive_com_port - {0}, negative_com_port - {1}, voltage - {2}", positive_com_port, negative_com_port, voltage)
    acq_controll = webapi.pai_global.get_value("AcquisitionControl")
    status = acq_controll.setVoltage(positive_com_port, negative_com_port, voltage)

    if status:
        return make_response(f"set voltage {voltage} successfully", 200)
    else:
        return make_response(f"set voltage {voltage} failed", 500)

def operate_mmscm(operation, mmscm_com_port, delay_time_us):
    logger.debug("MMSCM operation: {0}, query parameters: mmscm_com_port - {1}, delay_time_us - {2}", operation, mmscm_com_port, delay_time_us)
    acq_controll = webapi.pai_global.get_value("AcquisitionControl")
    status = False

    if operation == "open_mmscm_com_port":
        status = acq_controll.openMMSCMComPort(mmscm_com_port)
        #For safety, close qswitch and close flash when open the serial port
        acq_controll.closeQSwitch()
        acq_controll.closeFlash()
    elif operation == "open_flash":
        status = acq_controll.openFlash()
    elif operation == "open_qswitch":
        status = acq_controll.openQSwitch(delay_time_us)
    elif operation == "close_qswitch":
        status = acq_controll.closeQSwitch()
    elif operation == "close_flash":
        status = acq_controll.closeFlash()
    else:
        abort("wrong MMSCM operation.", 400)
    
    if not status:
        return make_response(f"operate MMSCM: {operation} failed.", 500)
    else:
        return make_response(f"OK. operate MMSCM:{operation} successfully", 200)

## operate the acquisition. operation可能为acq_progress, cancel_acquisition
def operate_acquisition(operation):
    logger.debug("start operate_acquisition. operation: {0}", operation)

    acq_controll = webapi.pai_global.get_value("AcquisitionControl")
    if operation == "acq_progress":
        acq_progress = acq_controll.getAcquisitionProgress()
        progress = {"acq_progress": acq_progress}
        logger.debug("end operate_acquisition. operation: {0}, progress:{1}", operation, acq_progress)
        return progress, 200
    elif operation == "cancel_acquisition":
        acq_controll.endAcquisition()
        #For safety, close qswitch and close flash when the acquisition ends
        acq_controll.closeQSwitch()
        acq_controll.closeFlash()
        return make_response("OK. end acquisition successfully", 200)
    else:
        abort("wrong acquisition operation.", 400)

## acquisition_method 可能为 ALL, single_angle_plane_wave, multi_angle_compound_plane_wave, single_shot_multiple_receive
def get_acquisition_method(acquisition_method):
    logger.debug("acquisition method: {0}", acquisition_method)
    acq_controll = webapi.pai_global.get_value("AcquisitionControl")

    if acquisition_method == "ALL":
        all_acquisition_methods = acq_controll.getAllAcquisitionMethods()
        return all_acquisition_methods
    else:
        acquisition_setting = acq_controll.getAcquisitionMethodSetting(acquisition_method)
        if acquisition_setting is None:
            abort("There is no acquisition setting for the input acquisition method. Please check whether the input acquisiton method is supported!", 500)
        else:
            return acquisition_setting

# 获取串口
# 检查激光器串口，关闭flash， qswitch
def system_initialization():
    acq_controll = webapi.pai_global.get_value("AcquisitionControl")
    acq_controll.initSystem()
    return "init system", 201


# 优雅的关闭
# 关闭激光器串口，关闭flash， qswitch
# 关闭matlab engine
#TODO
def system_finalization():
    print("Ctrl+C")
    #pai_acq.terminate_runtime()
    acq_controll = webapi.pai_global.get_value("AcquisitionControl")
    return "finalize system", 201


if __name__ == "__main__":
    pass